package com.ruslan.magaz.web;

import java.lang.annotation.Annotation;
import java.util.List;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import org.springframework.beans.factory.annotation.Autowired;

import com.ruslan.magaz.domain.User;
import com.ruslan.magaz.service.UserService;

public class UserExistsConstraintValidator implements
		ConstraintValidator<UserExistsConstraint, User> {

	@Autowired
	private UserService userService;

	@Override
	public void initialize(UserExistsConstraint constraint) {

	}

	@Override
	public boolean isValid(User user, ConstraintValidatorContext context) {

		try {
			return !nameExists(user);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return true;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}
	
	private boolean nameExists(User user) throws Exception{
		List<User> oldUsers = userService.getUserByName(user.getName());
		for (User oldUser : oldUsers) {
			if (oldUser.getUserId() != user.getUserId()) {
				return true;
			}
		}
		return false;
	}


}